package com.mrli.cat.weather.activity;

import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;

import com.mrli.cat.weather.R;
import com.mrli.cat.weather.database.WeatherProvider;
import com.mrli.cat.weather.service.LocationService;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class InItApplication extends Application {
    @Override
    public void onCreate() {
        SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(ForecastFragment.INIT_SHAREDPREFERENCE, Context.MODE_PRIVATE);
        if (sharedPreferences.getBoolean(WeatherPreferenceActivity.INIT_KEY, true)) {
            //初始化数据库
            new InitDataBase().execute();
            //启动定位服务
            Intent intent = new Intent(getApplicationContext(), LocationService.class);
            startService(intent);
        }
    }

    class InitDataBase extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            InputStream inputStream = null;
            FileOutputStream outputStream = null;
            try {
                outputStream = getApplicationContext().openFileOutput(WeatherProvider.CITY_DATABASE_NAME, MODE_PRIVATE);
                inputStream = getApplicationContext().getResources().openRawResource(R.raw.city);
                byte[] buffer = new byte[1024];
                int count = 0;
                while ((count = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }
    }

}
